import React from 'react';
import { Button, Tag, Balloon } from '@teamix/ui';
import { YunxiaoList, Header, Body, BodyContent, Content } from '@alife/devops-ui';
import TextAvatar from '@txdfe/at-text-avatar';
import track from 'utils/track';
import { ENUM, ORGANIZATION_ADMIN_ROLES, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import ListEmpty from 'atComponents/ListEmpty';
import TagForFeature from 'components/tagForFeature';
import './index.scss';
import { navigate } from 'utils/router';
import SettingModal from 'components/projectSecuritySettingModal';
import intl from '../../../../../../../../locale';

const prefix = 'project-security-entry';

export default class projectSecurityEntry extends React.Component {
  state = {
    hidePlaceholder: false,
    isModalOpen: false,
    modalPlugin: {},
  };

  componentDidMount() {
    // 高度不够，底部图片隐藏
    window.addEventListener('resize', this.togglePlaceholder);
    this.togglePlaceholder();
  }

  togglePlaceholder = () => {
    const entryContainer = document.querySelector('.project-security-entry-container');
    if (!entryContainer) {
      return;
    }
    this.setState({
      hidePlaceholder: entryContainer.clientHeight < 570,
    });
  };

  closeModal = () => {
    this.setState({
      isModalOpen: false,
      modalPlugin: {},
    });
  };

  isAdmin = () => {
    const { projectInfo: project } = this.props;
    const { user_role } = window.FORCE.organization;
    return (
      access(ORGANIZATION_ADMIN_ROLES, user_role) ||
      access(PROJECT_ADMIN_ROLES, ENUM.access_level[project.access_level])
    );
  };

  lookMore = (plugin) => {
    track({
      action:
        plugin.key === 'dependency_analysis'
          ? 'know_more_dependency_check'
          : 'know_more_sensitive_info_check',
      page: 'Repo-Security',
      type: '',
      control: '',
    });
  };

  // 跳到源文件
  goProjectFile = () => {
    const { pathResource } = window.FORCE;
    navigate(`/${pathResource.fullPath}`);
  };

  getRightBtn = (plugin) => {
    const { pathResource } = window.FORCE;
    const isEmpty = pathResource.isEmpty === 'true';
    let rightBtn = null;
    if (isEmpty) {
      rightBtn = null;
    } else if (this.isAdmin()) {
      rightBtn = (
        <Button
          type="primary"
          onClick={() => {
            // navigate(plugin.setting_url, { state: { forceUpdate: true } });
            // 此处出现modal
            this.setState({
              isModalOpen: true,
              modalPlugin: plugin,
            });

            track({
              action:
                plugin.key === 'dependency_analysis'
                  ? 'turn_on_dependency_check'
                  : 'turn_on_sensitive_info_check',
              page: 'Repo-Security',
              type: '',
              control: '',
            });
          }}
        >
          {intl.get({
            id: 'code-assets.containers.projectSecurityEntry.EnableNow',
            defaultMessage: '立即启用',
          })}
        </Button>
      );
    } else {
      rightBtn = (
        <span>
          {intl.get({
            id: 'code-assets.containers.projectSecurityEntry.ContactTheAdministratorToEnable',
            defaultMessage: '联系管理员开启',
          })}
        </span>
      );
    }
    return rightBtn;
  };

  getListDataSource = () => {
    const { plugins } = this.props;

    return plugins
      ? plugins.map((plugin) => ({
          left: <TextAvatar text={plugin.name} image={plugin.avatar_url} radius="4px" />,

          body: {
            title: (
              <span
                style={{
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {plugin.name}
                {plugin.isBeta && (
                  <TagForFeature
                    type="primary"
                    tagText={plugin.isBeta ? plugin.betaText : 'BETA'}
                  />
                )}
                {plugin.isCodeup ? (
                  <Tag>
                    {intl.get({
                      id: 'code-assets.containers.projectSecurityEntry.BuiltIn',
                      defaultMessage: '内置',
                    })}
                  </Tag>
                ) : (
                  <Balloon.Tooltip
                    align="t"
                    trigger={
                      <div className="flow-img-wrapper">
                        <img
                          className="flow-img"
                          src="https://tcs-devops.aliyun.com/thumbnail/111r5654e7a3c12aa319236976eb9530c2cf/w/88/h/88"
                        />
                      </div>
                    }
                  >
                    {intl.get({
                      id: 'code-assets.containers.projectSecurityEntry.CloudEffectPipelineFlowSupport',
                      defaultMessage: '云效流水线 Flow 支持',
                    })}
                  </Balloon.Tooltip>
                )}
              </span>
            ),

            description: [
              <span>
                {plugin.description}&nbsp;
                {plugin.desc_url ? (
                  <a
                    href={plugin.desc_url}
                    target="_blank"
                    onClick={() => {
                      this.lookMore(plugin);
                    }}
                    rel="noreferrer"
                  >
                    {intl.get({
                      id: 'code-assets.containers.projectSecurityEntry.LearnMore',
                      defaultMessage: '了解更多',
                    })}
                  </a>
                ) : null}
              </span>,
            ],
          },

          right: {
            items: [<span>{this.getRightBtn(plugin)}</span>],
          },
        }))
      : [];
  };

  render() {
    const { pathResource } = window.FORCE;
    const isEmpty = pathResource.isEmpty === 'true';
    const { hidePlaceholder, isModalOpen, modalPlugin } = this.state;
    const { serviceData, plugins } = this.props;
    const dataSource = this.getListDataSource();
    return (
      <div className={`${prefix}-container ${isEmpty ? 'empty' : ''}`}>
        {isEmpty && (
          <div className="empty-security">
            <ListEmpty
              content=""
              desc={intl.get({
                id: 'code-assets.containers.projectSecurityEntry.ProvideASetOfIntelligent',
                defaultMessage: '提供安全领域智能化检测工具集，保卫你的代码安全，我们全力以赴',
              })}
              btns={[
                <Button type="primary" onClick={this.goProjectFile}>
                  {intl.get({
                    id: 'code-assets.containers.projectSecurityEntry.InitializeARepository',
                    defaultMessage: '初始化仓库',
                  })}
                </Button>,
              ]}
              image="https://img.alicdn.com/tfs/TB1J2B8yUT1gK0jSZFrXXcNCXXa-486-442.png"
            />

            <div className="empty-security-list">
              {plugins.map((plugin) => {
                return (
                  <div className="empty-security-list-item">
                    <div className="empty-security-list-item-left">
                      <TextAvatar text={plugin.name} image={plugin.avatar_url} radius="4px" />
                    </div>
                    <div className="empty-security-list-item-right">
                      <div className="title">
                        {plugin.name}
                        {plugin.isBeta && (
                          <TagForFeature
                            type="primary"
                            tagText="BETA"
                          />
                        )}
                      </div>
                      <div className="desc">
                        {plugin.simple_desc}&nbsp;
                        {plugin.desc_url ? (
                          <a
                            href={plugin.desc_url}
                            target="_blank"
                            onClick={this.lookMore}
                            rel="noreferrer"
                          >
                            {intl.get({
                              id: 'code-assets.containers.projectSecurityEntry.LearnMore',
                              defaultMessage: '了解更多',
                            })}
                          </a>
                        ) : null}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {!isEmpty && (
          <>
            <Header
              title={intl.get({
                id: 'code-assets.containers.projectSecurityEntry.Safety',
                defaultMessage: '安全',
              })}
            />
            <Body>
              <BodyContent>
                <Content>
                  <YunxiaoList
                    dataSource={dataSource}
                    renderItem={(item) => (
                      <YunxiaoList.Item
                        title={item.body.title}
                        cover={item.left}
                        description={item.body.description[0]}
                        extra={
                          <>
                            <YunxiaoList.Item.Actions>{item.right.items}</YunxiaoList.Item.Actions>
                          </>
                        }
                      />
                    )}
                  />
                </Content>
              </BodyContent>
            </Body>
          </>
        )}

        <div className={`${prefix}-placeholder ${isEmpty || hidePlaceholder ? 'empty' : ''}`}>
          <div className={`${prefix}-placeholder-title`}>
            {intl.get({
              id: 'code-assets.containers.projectSecurityEntry.MoreSecurityCapacityBuilding',
              defaultMessage: '更多安全能力建设中…',
            })}
          </div>
          <div className={`${prefix}-placeholder-dot`}>
            <div className={`${prefix}-placeholder-dot-item`} />
            <div className={`${prefix}-placeholder-dot-item`} />
            <div className={`${prefix}-placeholder-dot-item`} />
            <div className={`${prefix}-placeholder-dot-item`} />
          </div>
        </div>
        {isModalOpen && (
          <SettingModal
            closeModal={this.closeModal}
            isModalOpen={isModalOpen}
            modalPlugin={modalPlugin}
            data={serviceData}
          />
        )}
      </div>
    );
  }
}
